//
//  PickNumShuangSeQiuViewController.m
//  PlayBall
//
//  Created by Edward Zhang on 12-5-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "JddPickNumShuangSeQiuViewController.h"
#import "JddViewControllerManager.h"
#import "JddCommonFunction.h"
#import "NoticeViewController.h"

@interface JddPickNumShuangSeQiuViewController ()
@end

@implementation JddPickNumShuangSeQiuViewController

@synthesize countlabel;
@synthesize moneylabel;
@synthesize issueCodeLabel;
@synthesize remainTimeLabel;
@synthesize currentLotteryIssue;

SHARED_VIEW_CONTROLLER_IMPLEMENT(JddPickNumShuangSeQiuViewController);

- (void)RandomSelectNumViewClickedButtonAtIndex:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    if ([buttonIndex intValue]== 1) {
        
        [lotteryNumberArray removeAllObjects];
        
        for (int i = 0; i < [multiple intValue]; ++i) {
            JddShuangSeQiuNumber *number = [[JddShuangSeQiuNumber alloc] init];
            [JddCommonFunction generateBlueBallOfShuangSeQiuNumber:number count:1];
            [JddCommonFunction generateRedBallOfShuangSeQiuNumber:number count:6];
            
            [lotteryNumberArray addObject:number];
        }
        
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SHUANGSEQIU_LIST 
                                                             fromController:self
                                                                 withObject:lotteryNumberArray
                                                                withObject2:nil];
    }
}

-(void)destoryView{
    [lotteryNumber clear];
    countlabel.text = @"0";
    moneylabel.text = @"0";
    [UIAccelerometer sharedAccelerometer].delegate = nil;
    sharked = true;
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]] || 
            subView.tag == 88 ||
            subView.tag == 99) {
            [((UIButton*)subView) setSelected:NO];
        }
    }

}

-(IBAction)randomSelect:(id)sender{
    
    [lotteryNumberArray removeAllObjects];
    
    for (int i = 0; i < 5; ++i) {
        JddShuangSeQiuNumber *number = [[JddShuangSeQiuNumber alloc] init];
        [JddCommonFunction generateBlueBallOfShuangSeQiuNumber:number count:1];
        [JddCommonFunction generateRedBallOfShuangSeQiuNumber:number count:6];
        
        [lotteryNumberArray addObject:number];
    }
    
    [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SHUANGSEQIU_LIST
                                                            fromController:self
                                                                withObject:lotteryNumberArray
                                                               withObject2:nil];

}
-(IBAction)clearSelect:(id)sender{
    [lotteryNumber clear];
    countlabel.text = @"0";
    moneylabel.text = @"0";
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]] || 
            subView.tag == 88 ||
            subView.tag == 99) {
            [((UIButton*)subView) setSelected:NO];
        }
    }
}
-(IBAction)sureSelect:(id)sender{
    if ([[JddPickNumShuangSeQiuListViewController sharedInstance].numberListTable numberOfRowsInSection:0]>0) {
        if ([lotteryNumber.redBallArray count]>0||[lotteryNumber.blueBallArray count]>0) {
            if ([lotteryNumber.redBallArray count] < 6) {
                [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_RED];
                return;
            } else if ([lotteryNumber.blueBallArray count] < 1) {
                [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_BLUE];
                return;
            }else {
                [lotteryNumberArray removeAllObjects];
                JddShuangSeQiuNumber *newNumber = [[JddShuangSeQiuNumber alloc] init];
                [newNumber.blueBallArray addObjectsFromArray:lotteryNumber.blueBallArray];
                [newNumber.redBallArray addObjectsFromArray:lotteryNumber.redBallArray];
                
                [lotteryNumberArray addObject:newNumber];
                [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SHUANGSEQIU_LIST 
                                                                     fromController:self 
                                                                         withObject:lotteryNumberArray 
                                                                        withObject2:nil];
            }
            
            
        }else if ([lotteryNumber.redBallArray count]==0&&[lotteryNumber.blueBallArray count]==0) {
            [[JddViewControllerManager sharedInstance].navigationController pushViewController:[JddPickNumShuangSeQiuListViewController sharedInstance] animated:YES];
        }                
    }else {
        
        if ([lotteryNumber.redBallArray count] < 6) {
            [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_RED];
            return;
        } else{
            if ([lotteryNumber.blueBallArray count] < 1) {
                [JddCommonFunction messageBoxWithMessage:BALL_COUNT_NOT_CORRECT_BLUE];
                return;
            }
        }
        [lotteryNumberArray removeAllObjects];
        JddShuangSeQiuNumber *newNumber = [[JddShuangSeQiuNumber alloc] init];
        [newNumber.blueBallArray addObjectsFromArray:lotteryNumber.blueBallArray];
        [newNumber.redBallArray addObjectsFromArray:lotteryNumber.redBallArray];
        
        [lotteryNumberArray addObject:newNumber];
        [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:CONTROLLER_PICK_NUM_SHUANGSEQIU_LIST 
                                                             fromController:self 
                                                                 withObject:lotteryNumberArray 
                                                                withObject2:nil];
    }

}

- (IBAction)numberButtonClicked:(id)sender{
    UIButton *button = sender;
    
    if (button.tag == 88) {
        
            [button setSelected:![button isSelected]];
        if ([button isSelected]) {
            if ([lotteryNumber.redBallArray count]>19) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                                message:@"红球最多选择20个"
                                                               delegate:self 
                                                      cancelButtonTitle:@"确定" 
                                                      otherButtonTitles:nil,nil ];
                [alert show];
                [button setSelected:![button isSelected]];
            }else {
            [lotteryNumber addRedBallNumber:[button.titleLabel.text intValue]];
            }
        }
        else {
            [lotteryNumber removeRedBallNumber:[button.titleLabel.text intValue]];
        }
        
    }
    
    if (button.tag == 99) {
        [button setSelected:![button isSelected]];
        if ([button isSelected]) {
            [lotteryNumber addBlueBallNumber:[button.titleLabel.text intValue]];
        }
        else {
            [lotteryNumber removeBlueBallNumber:[button.titleLabel.text intValue]];
        }
    }
    if(button.selected)
    {
        [JddCommonFunction animationViewWithZoomOutIn:button delaySecond:0];
    }
    self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]];
    self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]*2];
}

- (IBAction)randomSelectRedBall:(id)sender{  
    
//    CGRect rect = [[UIScreen mainScreen] bounds];
//    rect.origin.x = (rect.size.width - 251) / 2.0;
//    rect.origin.y = (rect.size.height - 139) / 2.0;
//    rect.size.width = 251.0;
//    rect.size.height = 139.0;
//    randomSelectNumberDialog = [JddRandomSelectNumView getInstanceView];;
//    [randomSelectNumberDialog setFrame:rect];
//    randomSelectNumberDialog.type =2;
//    randomSelectNumberDialog.multipleTextField.text = @"6";
//    randomSelectNumberDialog.typelabel.text = @"红球至少机选6个号码";
//    randomSelectNumberDialog.delegate = self;
    [randomSelectNumberDialog show];
    [self selectRedBall:[NSNumber numberWithInt:1] multiple:[NSNumber numberWithInt:6]];
    [self selectBlueBall:[NSNumber numberWithInt:1] multiple:[NSNumber numberWithInt:1]];
    
}

-(void)selectRedBall:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    [lotteryNumber clearRedBallNumber];
    if ([buttonIndex intValue] == 1) {
    [JddCommonFunction generateRedBallOfShuangSeQiuNumber:lotteryNumber count:[multiple intValue]];
    float delay = 0;
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 88) {
            BOOL shouldSelected = NO;
            
            if ([lotteryNumber redBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                shouldSelected = YES;
                [JddCommonFunction animationViewWithZoomOutIn:subView delaySecond:(delay+=0.05)];
            }
            
            [((UIButton*)subView) setSelected:shouldSelected];
        }

    }
    self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]];
    self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]*2];
    }
}

-(void)selectBlueBall:(NSNumber*)buttonIndex multiple:(NSNumber*)multiple{
    [lotteryNumber clearBlueBallNumber];
    if ([buttonIndex intValue] == 1) {
        [JddCommonFunction generateBlueBallOfShuangSeQiuNumber:lotteryNumber count:[multiple intValue]];
        float delay = 0;
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 99) {
                BOOL shouldSelected = NO;
                
                if ([lotteryNumber blueBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                    [JddCommonFunction animationViewWithZoomOutIn:subView delaySecond:(delay+=0.05)];
                }
                
                [((UIButton*)subView) setSelected:shouldSelected];
            }
        }
        self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]];
        self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]*2];

    }
}

- (IBAction)randomSelectBlueBall:(id)sender{
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect.origin.x = (rect.size.width - 251) / 2.0;
    rect.origin.y = (rect.size.height - 139) / 2.0;
    rect.size.width = 251.0;
    rect.size.height = 139.0;
    randomSelectNumberDialog = [JddRandomSelectNumView getInstanceView];;
    [randomSelectNumberDialog setFrame:rect];
    randomSelectNumberDialog.type =3;
    randomSelectNumberDialog.typelabel.text = @"蓝球至少机选1个号码";
    randomSelectNumberDialog.delegate = self;
    [randomSelectNumberDialog show];
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
    

    static NSDate *shakeStart;
    NSDate *now = [[NSDate alloc] init];
    NSDate *checkDate = [[NSDate alloc] initWithTimeInterval:1.5f sinceDate:shakeStart];
    if ([now compare:checkDate] == NSOrderedDescending || shakeStart == nil)
    {
        shakeCount = 0;
        shakeStart = [[NSDate alloc] init];
    }

    if (!sharked&&(fabsf(acceleration.x) > 1.0 || fabsf(acceleration.y) > 1.0 || fabsf(acceleration.z) > 1.1))
    {
        shakeCount++;
    }
    
    if (shakeCount > 0)
    {
        shakeCount = 0;
        shakeStart = [[NSDate alloc] init];
        [lotteryNumber clearRedBallNumber];
        [JddCommonFunction generateRedBallOfShuangSeQiuNumber:lotteryNumber count:6];
        
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 88) {
                BOOL shouldSelected = NO;
                
                if ([lotteryNumber redBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                }
                
                [((UIButton*)subView) setSelected:shouldSelected];
            }
        }
        
        [lotteryNumber clearBlueBallNumber];
        [JddCommonFunction generateBlueBallOfShuangSeQiuNumber:lotteryNumber count:1];
        
        for (UIView *subView in self.view.subviews) {
            if ([[subView class] isSubclassOfClass:[UIButton class]] && subView.tag == 99) {
                BOOL shouldSelected = NO;
                
                if ([lotteryNumber blueBallHasNumber:[((UIButton*)subView).titleLabel.text intValue]]) {
                    shouldSelected = YES;
                }
                
                [((UIButton*)subView) setSelected:shouldSelected];
            }
        }


        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
        
        self.countlabel.text=[NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]];
        self.moneylabel.text = [NSString stringWithFormat:@"%d", [JddCommonFunction countShuangSeQiuTotalNumber:[lotteryNumber.redBallArray count] blueBallAmount:[lotteryNumber.blueBallArray count]]*2];
    }
   
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)listSelect{
    NoticeViewController *noticeView = [[NoticeViewController alloc] init];
    noticeView.webInfoId = LOTTERY_TYPE_ID_SHUANGSEQIU;
    [self.navigationController pushViewController:noticeView animated:YES];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.message isEqualToString:@"您还没有登录，请先登录"]) {
        if (buttonIndex == 0) {
            [[JddViewControllerManager sharedInstance] pushViewControllerWithIndex:
             CONTROLLER_LOGIN 
                                                                 fromController:self
                                                                     withObject:nil 
                                                                    withObject2:nil];
        }
    }
}
- (void)loadNavBar
{
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 40, 30);
    [right setTitle:@"帮助" forState:UIControlStateNormal];
    right.titleLabel.font = [UIFont systemFontOfSize:15];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(listSelect) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:right];
    
}
//- (void)backView
//{
//    [self.navigationController popViewControllerAnimated:YES];
//}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    sharked = TRUE;
//    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"jdd_lb.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(listSelect)];
    [self loadNavBar];
    for (UIView *subView in self.view.subviews) {
        if ([[subView class] isSubclassOfClass:[UIButton class]]) {
            NSInteger number = [((UIButton*)subView).titleLabel.text intValue];
            int tagnumber = ((UIButton*)subView).tag;
            if (number > 0 && number < 34&&tagnumber == 88) {
                [((UIButton*)subView) setBackgroundImage:[UIImage imageNamed:@"jdd_redbollselected"] forState:UIControlStateSelected];
                [((UIButton*)subView) setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            }            if (number > 0 && number < 34&&tagnumber == 99) {
                [((UIButton*)subView) setBackgroundImage:[UIImage imageNamed:@"jdd_bulebollselected.png"] forState:UIControlStateSelected];
                [((UIButton*)subView) setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            }
        }
    }
    

    
//    [self.navigationItem setTitle:PAGE_SHUANGSEQIU_PICK_NUMBER];
        UILabel *customLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        customLab.backgroundColor = [UIColor clearColor];
        customLab.textAlignment = NSTextAlignmentCenter;
        [customLab setText:PAGE_SHUANGSEQIU_PICK_NUMBER];
        customLab.textAlignment = NSTextAlignmentCenter;

        [customLab setTextColor:[UIColor whiteColor]];
        customLab.font = [UIFont systemFontOfSize:19];
        self.navigationItem.titleView = customLab;

    currentLotteryIssue = [[JddLotteryIssue alloc] init];
    lotteryNumber = [[JddShuangSeQiuNumber alloc] init];
    lotteryNumberArray = [NSMutableArray array];
    
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
}

- (void)countDownTimer:(NSTimer*)thisTimer{
    currentTime = [currentTime dateByAddingTimeInterval:1];
    
    NSTimeInterval interval = [endTime timeIntervalSinceDate:currentTime];
    if (interval < 0) {
        [self requestQueryDigitalLotteryIssueOperation];
    }else {
        NSInteger remainDay = interval / 86400;
        NSInteger remainHour = (interval - 86400 * remainDay) / 3600;
        NSInteger remainMinute = (interval - 86400 * remainDay - remainHour * 3600) / 60;
        NSInteger remainSecond = (interval - 86400 * remainDay - remainHour *3600 - remainMinute * 60);
        remainTimeLabel.text = [NSString stringWithFormat:@"%d天%d小时%d分%d秒", remainDay, remainHour, remainMinute, remainSecond];
    }
}

- (void)QueryDigitalLotteryIssueOperationResult:(NSData *)result{
    if (result) {
        if ([JddDataParser parseLotteryIssueResult:result lotteryIssue:currentLotteryIssue]){
            issueCodeLabel.text = [NSString stringWithFormat:@"第%@期",currentLotteryIssue.name];
            
            endTime = [JddCommonFunction dateFromString:currentLotteryIssue.endTime];
            currentTime = [JddCommonFunction dateFromString:currentLotteryIssue.currentTime];
            
            countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 
                                                              target:self 
                                                            selector:@selector(countDownTimer:) 
                                                            userInfo:nil 
                                                             repeats:YES]; 
        }
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:@"SSQ"];
    
    [countDownTimer invalidate];
    [UIAccelerometer sharedAccelerometer].delegate = nil;
    sharked = true;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"SSQ"];
	[MobClick event:@"Lottery-SSQ"];
    
    [[UIAccelerometer sharedAccelerometer] setDelegate:self];
    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:1.0];
    shakeCount = 0;
    sharked = false;
    [self requestQueryDigitalLotteryIssueOperation];
    [self randomSelectRedBall:nil];
}

-(void)requestQueryDigitalLotteryIssueOperation
{
    [countDownTimer invalidate];
    JddQueryDigitalLotteryIssueOperation *operation = [[JddQueryDigitalLotteryIssueOperation alloc] init];
    operation.delegate = self;
    operation.lotteryTypeId = @"5";
    [[JddGlobalParameter sharedInstance].operationQueue addOperation:operation];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
